package a2;

import java.util.List;

import org.openrdf.query.BindingSet;
import org.openrdf.query.QueryLanguage;
import org.openrdf.query.TupleQuery;
import org.openrdf.query.TupleQueryResult;
import org.openrdf.repository.Repository;
import org.openrdf.repository.RepositoryConnection;

public class SPARQLQueryHandler {

	/**
	 * Returns the result of a SPARQL query from the specified repository
	 * @param query The query string
	 * @param repository The target repository
	 * @return A string representing the result of the query
	 */
	public static String performQuery(String query, Repository repository) {
		RepositoryConnection con;
		StringBuilder sb = new StringBuilder();
		String separator = "\t";

		try {
			repository.initialize();
			con = repository.getConnection();
			try {
				TupleQuery tupleQuery = con.prepareTupleQuery(
						QueryLanguage.SPARQL, query);
				TupleQueryResult result = tupleQuery.evaluate();
				List<String> bindingNames = result.getBindingNames();

				// Headers
				for (int i = 0; i < bindingNames.size(); ++i) {
					sb.append(bindingNames.get(i));
					if (i < bindingNames.size() - 1) {
						sb.append(separator);
					}
				}

				sb.append("\n");

				// Results
				while (result.hasNext()) {
					BindingSet bindingSet = result.next();
					String value = "";
					for (int i = 0; i < bindingNames.size(); ++i) {
						value = bindingSet.getValue(bindingNames.get(i))
								.stringValue();
						int cutIndex = value.indexOf('#');
						value = value.substring(cutIndex + 1);
						sb.append(value);
						if (i < bindingNames.size() - 1) {
							sb.append(separator);
						}
					}
					sb.append("\n");
				}

				result.close();
			} finally {
				con.close();
				repository.shutDown();
			}
		} catch (Exception e) {
			System.out.println("Something went wrong.");
		}
		return sb.toString();
	}

}
